package org.example.controller;

import org.example.service.UserService;
import org.example.service.DeviceService;
import org.example.service.ServiceRequestService;
import org.example.service.SceneService;
import org.example.device.sync.DeviceStatusSyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员控制器
 */
@RestController
@RequestMapping("/api/admin")
@CrossOrigin(origins = "*")
public class AdminController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private DeviceService deviceService;
    
    @Autowired
    private ServiceRequestService serviceRequestService;
    
    @Autowired
    private SceneService sceneService;
    
    @Autowired
    private DeviceStatusSyncService deviceStatusSyncService;

    /**
     * 获取管理员仪表板统计数据
     */
    @GetMapping("/dashboard/stats")
    public ResponseEntity<?> getAdminDashboardStats() {
        try {
            Map<String, Object> stats = new HashMap<>();
            
            // 用户统计
            long totalUsers = userService.countAllUsers();
            long activeUsers = userService.countActiveUsers();
            long adminUsers = userService.countByRole("ADMIN");
            long maintenanceUsers = userService.countByRole("MAINTENANCE");
            long normalUsers = userService.countByRole("USER");
            
            Map<String, Object> userStats = new HashMap<>();
            userStats.put("totalUsers", totalUsers);
            userStats.put("activeUsers", activeUsers);
            userStats.put("inactiveUsers", totalUsers - activeUsers);
            userStats.put("adminUsers", adminUsers);
            userStats.put("maintenanceUsers", maintenanceUsers);
            userStats.put("normalUsers", normalUsers);
            stats.put("userStats", userStats);
            
            // 设备统计
            Map<String, Object> deviceStats = deviceStatusSyncService.getDeviceStatusStats();
            stats.put("deviceStats", deviceStats);
            
            // 服务申请统计
            Map<String, Object> serviceStats = new HashMap<>();
            serviceStats.put("total", serviceRequestService.countByStatus("PENDING") + 
                             serviceRequestService.countByStatus("IN_PROGRESS") + 
                             serviceRequestService.countByStatus("COMPLETED") + 
                             serviceRequestService.countByStatus("CANCELLED"));
            serviceStats.put("pending", serviceRequestService.countByStatus("PENDING"));
            serviceStats.put("inProgress", serviceRequestService.countByStatus("IN_PROGRESS"));
            serviceStats.put("completed", serviceRequestService.countByStatus("COMPLETED"));
            serviceStats.put("cancelled", serviceRequestService.countByStatus("CANCELLED"));
            serviceStats.put("urgent", serviceRequestService.countByUrgencyLevel("URGENT"));
            serviceStats.put("veryUrgent", serviceRequestService.countByUrgencyLevel("VERY_URGENT"));
            stats.put("serviceStats", serviceStats);
            
            // 场景统计
            Map<String, Object> sceneStats = new HashMap<>();
            sceneStats.put("totalScenes", sceneService.countAllScenes());
            sceneStats.put("activeScenes", sceneService.countActiveScenes());
            sceneStats.put("inactiveScenes", sceneService.countAllScenes() - sceneService.countActiveScenes());
            stats.put("sceneStats", sceneStats);
            
            return ResponseEntity.ok(stats);
            
        } catch (Exception e) {
            return ResponseEntity.status(500).body("获取管理员统计数据失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取用户列表（管理员专用）
     */
    @GetMapping("/users")
    public ResponseEntity<?> getAllUsers() {
        try {
            return ResponseEntity.ok(userService.findAllUsers());
        } catch (Exception e) {
            return ResponseEntity.status(500).body("获取用户列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有设备（管理员专用）
     */
    @GetMapping("/devices")
    public ResponseEntity<?> getAllDevices() {
        try {
            return ResponseEntity.ok(deviceService.findAllDevices());
        } catch (Exception e) {
            return ResponseEntity.status(500).body("获取设备列表失败：" + e.getMessage());
        }
    }
    
    /**
     * 获取所有服务申请（管理员专用）
     */
    @GetMapping("/service-requests")
    public ResponseEntity<?> getAllServiceRequests() {
        try {
            return ResponseEntity.ok(serviceRequestService.findAllServiceRequests());
        } catch (Exception e) {
            return ResponseEntity.status(500).body("获取服务申请列表失败：" + e.getMessage());
        }
    }
}
